package com.uclocation.DAO;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.uclocation.DTO.UCLocation;

/**
 * 
 * @author Rico
 * Our DAO stub.  This implements the methods from the DAO interface.  Retrieves and Inserts data to our Database.
 */
public class UCLocationDAOStub extends SQLiteOpenHelper implements IUCLocationDAO {
	
	public UCLocationDAOStub(Context context) {
		super(context,"UCLocationDAO", null, 1);
		
	}

	private static final String NICK_NAME = "NickName";
	private static final String ADDRESS = "Address";
	private static final String ADDRESS_TBL = "addressTBL";
	
	
	

	@Override
 public UCLocation selectAddress(String addressNickName) throws Exception {
		UCLocation ucLocation = null;
		//SQL statement that is used to attempt to select the passed in addressNickName
		String getAddressSQL = "SELECT * FROM " + ADDRESS_TBL + " WHERE " + NICK_NAME + " = " + addressNickName;
		// Get the result set.  Should be either 1 or no results.
		Cursor cursor = getReadableDatabase().rawQuery(getAddressSQL, null);
		
		// Does the DB have a NickName that matches the one that is passed in?
		if (cursor.getCount() > 0) {
		cursor.moveToFirst();
		ucLocation = new UCLocation();
		
		ucLocation.setNickName(cursor.getString(1));
		ucLocation.setLocation(cursor.getString(2));
		
		cursor.close();
		}
		return ucLocation;
	}
		

	@Override
	public void addAddress(UCLocation location) throws Exception {
		String testNickName = location.getNickName();
		String getAddressSQL = "SELECT * FROM " + ADDRESS_TBL + " WHERE " + NICK_NAME + " = " + testNickName;
		Cursor cursor = getReadableDatabase().rawQuery(getAddressSQL, null);
		//checks if nickname is already used
		if (cursor.getCount() > 0){
			throw new Exception("NickName already used! Choose another NickName");
		}
		ContentValues values = new ContentValues();
		values.put(ADDRESS, location.getAddress());
		values.put(NICK_NAME, location.getNickName());
		
		getWritableDatabase().insert(ADDRESS_TBL, null, values);
		cursor.close();

	}

	

	@Override
	public void onCreate(SQLiteDatabase dB) {
		//SQL to create DB for the first time
		String createDBSQL = "CREATE TABLE " + ADDRESS_TBL + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT," + 
		NICK_NAME + " TEXT, " + ADDRESS + " TEXT, " + ");";
		//executes SQL code
		dB.execSQL(createDBSQL);
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

}
